package cn.com.acca.ma.service.impl;

import cn.com.acca.ma.common.util.DateUtil;
import cn.com.acca.ma.common.util.PropertiesUtil;
import cn.com.acca.ma.constant.*;
import cn.com.acca.ma.model.ModelGoldCrossDeadCrossAnalysis;
import cn.com.acca.ma.model.Robot3StockTransactRecord;
import cn.com.acca.ma.model.RobotStockTransactionRecord;
import cn.com.acca.ma.pojo.*;
import cn.com.acca.ma.service.Robot3StockTransactRecordService;
import cn.com.acca.ma.service.RobotStockTransactionRecordService;

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

public class Robot3StockTransactRecordServiceImpl extends BaseServiceImpl<Robot3StockTransactRecordServiceImpl, Robot3StockTransactRecord> implements
        Robot3StockTransactRecordService {

    /**
     * 执行某段时间内的股票买卖交易（周线级别布林带突破上轨或跌破下轨）
     */
    @Override
    public void doBuyAndSellByBeginDateAndEndDate_weekBoll() {
        logger.info("执行某段时间内的股票买卖交易（周线级别布林带突破上轨或跌破下轨）");

        String weekBollBeginDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.beginDate");
        String weekBollEndDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.endDate");
        Integer operationDirection = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.operationDirection"));
        Integer closePriceUpDownBollDateNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.up.down.boll.date.number"));
        Double closePricePercentageFromUpDn = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.percentage.from.up.dn"));
        Double closePriceStart = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.start"));
        Double closePriceEnd = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.end"));
        Integer kdTop = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.kd.top"));
        Integer kdBottom = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.kd.bottom"));
        String xrBeginDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.xr.begin.date");
        String currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.current.closePrice.compareTo.someTime.highest.lowest.price.begin.date");
        Integer currentClosePriceCompareToSomeTimeHighestPrice = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.current.closePrice.compareTo.someTime.highest.price"));
        Integer currentClosePriceCompareToSomeTimeLowestPrice = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.current.closePrice.compareTo.someTime.lowest.price"));
        Double closePriceGreatThenMA250Rate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.greatThen.lessThen.ma250.rate"));
        Integer backwardMonth = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.closePrice.greatThen.lessThen.ma250.backward.month"));
        String maNotIncreasingLevel = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.averageGoldCrossDeadCross.ma.not.increasing.level");
        String maNotIncreasingDateNumber = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.averageGoldCrossDeadCross.ma.not.increasing.dateNumber");
        String maNotDecreasingLevel = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.averageGoldCrossDeadCross.ma.not.decreasing.level");
        String maNotDecreasingDateNumber = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.averageGoldCrossDeadCross.ma.not.decreasing.dateNumber");
        Integer bollUpDnDirectionMethod = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.direction.method"));
        Integer shippingSpaceControl = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.shippingSpaceControl"));
        Integer mandatoryStopLoss = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.mandatoryStopLoss"));
        Double mandatoryStopLossRate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.mandatoryStopLossRate"));
        Integer holdStockNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.holdStockNumber"));
        Integer printFormat = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.sell.week.boll.print.format"));

        // 获取日期列表
        List<String> dateList = stockTransactionDataDao.findDistinctDateBetweenBeginDateAndEndDate(false, weekBollBeginDate, weekBollEndDate);

        if (null != dateList && dateList.size() > 0) {
            for (int i = 0; i < dateList.size(); i++) {
                String currentDate = dateList.get(i);
                String beginDate = DateUtil.dateToString(DateUtil.stepMonth(DateUtil.stringToDate(currentDate), -backwardMonth));

                /*************************************** 卖股票/买股票 ***********************************************/
                // 更新robot3_account表
                robot3AccountDao.updateRobotAccountBeforeSellOrBuy(currentDate);

                // 卖股票
                robot3StockTransactRecordDao.sellOrBuy(currentDate, mandatoryStopLoss, mandatoryStopLossRate);

                // 更新robot3_account表
                robot3AccountDao.updateRobotAccountAfterSellOrBuy(currentDate);

                // 如果所有账号都已经满仓，则跳过这个交易日
                if (isFullStockInRobot3Account(holdStockNumber)) {
                    logger.info("所有账号都是满仓，因此日期【" + currentDate + "】不做任何交易，直接跳过");

                    // 更新robot3_account表的total_assets字段
                    robot3AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                // 如果所有股票的平均收盘价在牛熊线之下，则跳过这个交易日
                if (robot3StockFilterDao.isUpBullShortLine(currentDate)) {
                    logger.info("所有股票的平均收盘价在牛熊线之下，因此日期【" + currentDate + "】不做任何交易，直接跳过");

                    // 更新robot3_account表的total_assets字段
                    robot3AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);

                    continue;
                }

                /********************************** 确定是做多，还是做空。判断使用哪种算法 ***********************************/
//                // 查询本周之前一周的开始时间和结束时间
//                StockWeekDatePojo stockWeekDatePojo = stockIndexWeekDao.findBeginDateAndEndDateInLastWeekByDate(currentDate);
//                // 查询本周之前一周，收盘价突破布林带上轨的股票的数量和收盘价跌破布林带下轨的股票的数量
//                StockWeekBollUpDnCount stockWeekBollUpDnCount = stockWeekDao.findStockWeekBollUpDnCount(stockWeekDatePojo.getBeginDate(), stockWeekDatePojo.getEndDate(), closePricePercentageFromUpDn);
//                logger.info("收盘价突破布林带上轨的股票数量为【" + stockWeekBollUpDnCount.getClosePriceUpBollStockCount() + "】，" +
//                        "收盘价跌破布林带下轨的股票数量为【" + stockWeekBollUpDnCount.getClosePriceDnBollStockCount() + "】");
//
//                // 查询当前日期之前的两条记录（包括当前日期）
//                List<ModelGoldCrossDeadCrossAnalysis> modelGoldCrossDeadCrossAnalysisList = modelGoldCrossDeadCrossAnalysisDao.findTwoByDateOrderByDateDesc(currentDate);
//                ModelGoldCrossDeadCrossAnalysis currentModelGoldCrossDeadCrossAnalysis = modelGoldCrossDeadCrossAnalysisList.get(0);
//                ModelGoldCrossDeadCrossAnalysis lastModelGoldCrossDeadCrossAnalysis = modelGoldCrossDeadCrossAnalysisList.get(1);
//
//                // 判断是做多，还是做空。判断使用哪种算法
//                FilterMethod.SELECT_FILTER_METHOD_VALUE = Double.MAX_VALUE;
//                FilterMethod.SELECT_FILTER_METHOD = null;
//                Double number = null;
//                // 做多还是做空。1表示做多，-1表示做空
                Integer bullOrShortDirection = null;
                // 做空
//                if (stockWeekBollUpDnCount.getClosePriceUpBollStockCount().compareTo(stockWeekBollUpDnCount.getClosePriceDnBollStockCount()) > 0) {
//                    logger.info("操作方向：做空");
//                    bullOrShortDirection = BullOrShortDirection.SHORT;

//                    // MACD死叉
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getMacdDeadCrossPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.MACD_DEAD_CROSS;
//                            }
//                        }
//                    }
//
//                    // close_price死叉ma5
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getClosePriceDeadCrossMA5PercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.CLOSE_PRICE_DEAD_CROSS_MA;
//                            }
//                        }
//                    }
//
//                    // hei_kin_ashi下跌趋势
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiDownUpPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.HEI_KIN_ASHI_DOWN_UP;
//                            }
//                        }
//                    }
//
//                    // kd死叉
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getKdDeadCrossPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.KD_DEAD_CROSS;
//                            }
//                        }
//                    }
//                }

                // 做多
//                if (stockWeekBollUpDnCount.getClosePriceUpBollStockCount().compareTo(stockWeekBollUpDnCount.getClosePriceDnBollStockCount()) <= 0)
//                {
//                    logger.info("操作方向：做多");
//                    bullOrShortDirection = BullOrShortDirection.BULL;

//                    // MACD金叉
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getMacdGoldCrossPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.MACD_GOLD_CROSS;
//                            }
//                        }
//                    }
//
//                    // close_price死叉ma5
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getClosePriceGoldCrossMA5PercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.CLOSE_PRICE_GOLD_CROSS_MA;
//                            }
//                        }
//                    }
//
//                    // hei_kin_ashi上涨趋势
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getHeiKinAshiUpDownPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.HEI_KIN_ASHI_UP_DOWN;
//                            }
//                        }
//                    }
//
//                    // kd金叉
//                    if ((currentModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA5().compareTo(currentModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA10()) >= 0)
//                            /*&& (lastModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA5().compareTo(lastModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA10()) < 0)*/) {
//                        number = currentModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA5().add(currentModelGoldCrossDeadCrossAnalysis.getKdGoldCrossPercentMA10()).divide(new BigDecimal(2)).doubleValue();
//                        if (number != 0) {
//                            if (number.compareTo(FilterMethod.SELECT_FILTER_METHOD_VALUE) < 0) {
//                                FilterMethod.SELECT_FILTER_METHOD_VALUE = number;
//                                FilterMethod.SELECT_FILTER_METHOD = FilterMethod.KD_GOLD_CROSS;
//                            }
//                        }
//                    }
//                }
//                if (null != FilterMethod.SELECT_FILTER_METHOD) {
//                    logger.info("操作算法：【" + FilterMethod.SELECT_FILTER_METHOD + "】，数值为【" + FilterMethod.SELECT_FILTER_METHOD_VALUE + "】");
//                } else {
//                    logger.info("应当使用的操作算法：【" + FilterMethod.SELECT_FILTER_METHOD + "】，由于【" + currentDate + "】没有合适的股票，因此没有操作");
//                }

                /*************************************** 按照条件，过滤股票 ***********************************/
//                if (null != FilterMethod.SELECT_FILTER_METHOD) {
                // 清空robot3_stock_filter表
                robot3StockFilterDao.truncateTableRobotStockFilter();
                // 根据date，从stock_transaction_data表中，向robot3_stock_filter表中插入股票代码
                robot3StockFilterDao.insertAllStockBollByDate(currentDate);

                // 金叉做多的算法
//                    if (1 == FilterMethod.SELECT_FILTER_METHOD % 2) {
//                    if (bullOrShortDirection.equals(BullOrShortDirection.BULL)) {
                // 根据date，从stock_transaction_data表中，向robot3_stock_filter表中插入股票代码
//                        robot3StockFilterDao.insertStockWeekBollDnByDate(DateUtil.dateToString(stockWeekDatePojo.getBeginDate()), DateUtil.dateToString(stockWeekDatePojo.getEndDate()));

                // 趋势行情
//                        if (bollUpDnDirectionMethod == BollUpDnDirectionMethod.FOLLOW_TREND_OPERATION){
                // 过滤条件：当前收盘价与某段时间最高价的百分比
//                            robotStockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeHighestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeHighestPrice);
//
                            // 过滤条件：MA不单调递减，过滤股票
                            String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
                            String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
                            for (int j=0; j<maLevelArray.length && j<dateNumberArray.length; j++){
                                String maLevel = maLevelArray[j].trim();
                                String dateNumber = dateNumberArray[j].trim();
                                robot3StockFilterDao.filterByMANotDecreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
                            }
//                        }
//                    }
                // 死叉做空的算法
//                    if (0 == FilterMethod.SELECT_FILTER_METHOD % 2) {
//                    if (bullOrShortDirection.equals(BullOrShortDirection.SHORT)) {
                // 根据date，从stock_transaction_data表中，向robot3_stock_filter表中插入股票代码
//                        robot3StockFilterDao.insertStockWeekBollUpByDate(DateUtil.dateToString(stockWeekDatePojo.getBeginDate()), DateUtil.dateToString(stockWeekDatePojo.getEndDate()));

                // 趋势行情
//                        if (bollUpDnDirectionMethod == BollUpDnDirectionMethod.FOLLOW_TREND_OPERATION){
                // 过滤条件：当前收盘价与某段时间最低价的百分比
//                            robotStockFilterDao
//                                    .filterByPercentageOfCurrentClosePriceCompareToSomeTimeLowestPrice(
//                                            currentClosePriceCompareToSomeTimeHighestLowestPriceBeginDate, currentDate,
//                                            currentClosePriceCompareToSomeTimeLowestPrice);
//
//                            // 过滤条件：MA不单调递增，过滤股票
//                            String[] maLevelArray = maNotDecreasingLevel.replace("[", "").replace("]", "").split(",");
//                            String[] dateNumberArray = maNotDecreasingDateNumber.replace("[", "").replace("]", "").split(",");
//                            for (int j=0; j<maLevelArray.length && j<dateNumberArray.length; j++){
//                                String maLevel = maLevelArray[j].trim();
//                                String dateNumber = dateNumberArray[j].trim();
//                                robot3StockFilterDao.filterByMANotIncreasing(currentDate, Integer.parseInt(maLevel), dateNumber);
//                            }
//                        }
//                    }
//
                // 只保留这个价格区间以内的股票
//                    robot3StockFilterDao.filterByLessThanClosePrice(currentDate, closePriceStart, closePriceEnd);

                // 震荡行情
//                    if (bollUpDnDirectionMethod == BollUpDnDirectionMethod.REVERSE_TREND_OPERATION){
//                        // 日线级别，某一段时间内，收盘价大于年线的记录数（数量更多）/收盘价小于年线的记录数（数量更少）<=阈值
//                        robot3StockFilterDao.filterByClosePriceGreatThenLessThenMA250(beginDate, currentDate, closePriceGreatThenMA250Rate);
//                    }

                // 过滤条件：删除除过权的股票
//                    robot3StockFilterDao.filterByXr(xrBeginDate, currentDate);
//                }

                /*************************************** 执行过滤算法 ***********************************/
//                if (bullOrShortDirection.equals(BullOrShortDirection.BULL)){
//                    robot3StockFilterDao.filterByAllGoldCross(currentDate);
//                }
//                if (bullOrShortDirection.equals(BullOrShortDirection.SHORT)){
//                    robot3StockFilterDao.filterByAllDeadCross(currentDate);
//                }
//                if (null != FilterMethod.SELECT_FILTER_METHOD) {
//                    // 过滤条件：MACD金叉
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.MACD_GOLD_CROSS)) {
//                        robot3StockFilterDao.filterByMACDGoldCross(currentDate);
//                    }
//                    // 过滤条件：收盘价金叉五日均线
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.CLOSE_PRICE_GOLD_CROSS_MA)) {
//                        robot3StockFilterDao.filterByClosePriceGoldCrossMA5(currentDate);
//                    }
//                    // 过滤条件：平均K线从下跌趋势变为上涨趋势
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.HEI_KIN_ASHI_UP_DOWN)) {
//                        robot3StockFilterDao.filterByHeiKinAshiUpDown(currentDate);
//                    }
//                    // 过滤条件：KD金叉
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.KD_GOLD_CROSS)) {
//                        robot3StockFilterDao.filterByKDGoldCross(currentDate);
//                    }
//                    // 过滤条件：MACD死叉
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.MACD_DEAD_CROSS)) {
//                        robot3StockFilterDao.filterByMACDDeadCross(currentDate);
//                    }
//                    // 过滤条件：收盘价死叉五日均线
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.CLOSE_PRICE_DEAD_CROSS_MA)) {
//                        robot3StockFilterDao.filterByClosePriceDeadCrossMA5(currentDate);
//                    }
//                    // 过滤条件：平均K线从上涨趋势变为下跌趋势
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.HEI_KIN_ASHI_DOWN_UP)) {
//                        robot3StockFilterDao.filterByHeiKinAshiDownUp(currentDate);
//                    }
//                    // 过滤条件：KD死叉
//                    if (FilterMethod.SELECT_FILTER_METHOD.equals(FilterMethod.KD_DEAD_CROSS)) {
//                        robot3StockFilterDao.filterByKDDeadCross(currentDate);
//                    }
//                }

                // 只保留这个价格区间以内的股票
                robot3StockFilterDao.filterByLessThanClosePrice(currentDate, closePriceStart, closePriceEnd);
                // 过滤条件：删除某一天所在的那周的kd平均值在kdAverageTop和kdAverageBottom之外的股票
//                robot3StockFilterDao.filterByStockWeekKDBetween(currentDate, kdTop, kdBottom);
                // 过滤条件：如果当前交易日和前一个交易日的收盘价都大于/小于布林带上轨/下轨，并且当前交易日的收盘价小于/大于前一个交易日的收盘价，则保留
                robot3StockFilterDao.filterByUpDownBoll(currentDate, closePriceUpDownBollDateNumber, operationDirection);
                // 过滤条件：删除除过权的股票
                robot3StockFilterDao.filterByXr(currentDate, weekBollEndDate);

                /*************************************** 买股票/卖股票 ******************************************/
//                if (null != FilterMethod.SELECT_FILTER_METHOD) {
//                if (null != bullOrShortDirection) {
                // 买股票/卖股票
                // 确定交易方向（做多/做空）
//                    Integer direction;
//                    if (0 == FilterMethod.SELECT_FILTER_METHOD % 2) {
//                    if (0 == bullOrShortDirection % 2) {
//                        direction = -1;
//                    } else {
//                        direction = 1;
//                    }
                // 因为选择金叉位置最低的，而金叉位置越低，表示未来成长空间越大，因此仓位也就越重，因此此处是100 - FilterMethod.SELECT_FILTER_METHOD_VALUE
//                    robot3StockTransactRecordDao.buyOrSell(currentDate, backwardMonth, null, FilterMethod.SELECT_FILTER_METHOD, 100 - FilterMethod.SELECT_FILTER_METHOD_VALUE, direction, shippingSpaceControl, holdStockNumber);
                robot3StockTransactRecordDao.buyOrSell(currentDate, backwardMonth, null, null, null, bullOrShortDirection, shippingSpaceControl, holdStockNumber, operationDirection);

                // 更新robot3_account表的total_assets字段
                robot3AccountDao.updateRobotAccountAfterBuyOrSell(currentDate);
//                }

                // 获取买卖建议
                String printText = null;
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.JSON)) {
                    // json方式
                    printText = super.printBuySellSuggestionByJson_weekBoll(currentDate);
                }
                if (printFormat.equals(RobotPrintBuySellSuggestionFormat.SIMPLE)) {
                    // 简单文本格式
                    printText = super.printBuySellSuggestionBySimple_weekBoll(currentDate);
                }
                logger.info("买卖建议：\n" + printText);
            }
        }

        logger.info("执行某段时间内的股票买卖交易完成（周线级别布林带突破上轨或跌破下轨）");
    }

    /**
     * 卖股票/买股票
     */
    @Override
    public void sellOrBuy() {
        logger.info("卖股票/买股票");

        String sellDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.sell.stock.date");
        Integer mandatoryStopLoss = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.sell.stock.mandatoryStopLoss"));
        Double mandatoryStopLossRate = Double.parseDouble(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.sell.stock.mandatoryStopLossRate"));

        robotStockTransactionRecordDao.sellOrBuy(sellDate, mandatoryStopLoss, mandatoryStopLossRate);
    }

    /**
     * 买股票/卖股票
     */
    @Override
    public void buyOrSell() {
        logger.info("买股票/卖股票");

        String buyDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.stock.date");
        Integer backwardMonth = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.stock.success.rate.backward.month"));
        Integer averageDateNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.stock.success.rate.average.date.number"));
//        Integer successRateType = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.stock.success.rate.type"));
        Integer successRateType = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.buy.shippingSpaceControl"));
        Integer shippingSpaceControl = FilterMethod.SELECT_FILTER_METHOD;
        Double successRate = FilterMethod.SELECT_FILTER_METHOD_VALUE;
        Integer holdStockNumber = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.holdStockNumber"));

        // 确定交易方向（做多/做空）
        Integer direction;
        if (0 == FilterMethod.SELECT_FILTER_METHOD % 2) {
            direction = -1;
        } else {
            direction = 1;
        }
        // 买股票
        robotStockTransactionRecordDao.buyOrSell(buyDate, backwardMonth, averageDateNumber, successRateType,
                successRate, direction, shippingSpaceControl, holdStockNumber);
    }

    /**
     * 打印买卖建议
     */
    @Override
    public void printBuySellSuggestion() {
        logger.info("打印买卖建议");

        String printDate = PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.print.day");
        Integer printFormat = Integer.parseInt(PropertiesUtil.getValue(MODEL_FILTER_PROPERTIES, "filter.print.format"));

        // 获取买卖建议
        String printText = null;
        if (printFormat.equals(RobotPrintBuySellSuggestionFormat.JSON)) {
            // json方式
            printText = super.printBuySellSuggestionByJson_weekBoll(printDate);
        }
        if (printFormat.equals(RobotPrintBuySellSuggestionFormat.SIMPLE)) {
            // 简单文本格式
            printText = super.printBuySellSuggestionBySimple_weekBoll(printDate);
        }
        System.out.println("买卖建议：\n" + printText);

        // 打印买卖建议
        File file;
        try {
            file = new File(PRINT_ROBOT_BUY_SELL_SUGGESTION);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileWriter writer = new FileWriter(file);
            writer.write(printText);
            writer.flush();
            writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public String listToString(List list) {
        return null;
    }
}
